import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/policy_entity.dart';
import 'package:factoryside/bean/userinfo_entity.dart';
import 'package:factoryside/generated/json/policy_entity_helper.dart';
import 'package:factoryside/home/page_address_list.dart';
import 'package:factoryside/provider/providers.dart';
import 'package:factoryside/utils/custom_path.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_save/image_save.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:http_parser/http_parser.dart';

class UserInfo extends StatefulWidget {
  @override
  _UserInfoState createState() => _UserInfoState();
}

class _UserInfoState extends State<UserInfo> {
  var userInfo;

  var avatarUrl;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar('个人信息', [], context),
      body: Container(
        color: Color(0xffEFEFEF),
        child: Consumer<User>(builder: (context,userInfo,child){
          UserinfoDataData userInfo=context.select((User user) => user.userInfo);
          return ListView(children: [
            Container(
              color: Colors.white,
              margin: EdgeInsets.symmetric(vertical: 10),
              child: Column(
                children: [
                  InkWell(
                    onTap: (){
                      showModalBottomSheet<int>(
                        context: context,
                        builder: (BuildContext context) {
                          return Container(
                            margin: EdgeInsets.all(10),
                            height: 56*2.toDouble(),
                            child: Column(
                              children: ListTile.divideTiles(tiles: [
                                ListTile(
                                  title: Center(child: Text("拍摄")),
                                  onTap: () {
                                    Navigator.of(context).pop();
                                    _getImage(ImageSource.camera);
                                  },
                                ),
                                ListTile(
                                    title: Center(child: Text("相册")),
                                    onTap: () {
                                      Navigator.of(context).pop();
                                      _getImage(ImageSource.gallery);
                                    })
                              ],color: Colors.grey).toList(),
                            ),
                          );
                        },
                        elevation: 10,
                        backgroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
                      );
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(10),
                      child: Row(children: [
                        Expanded(child: Text('头像')),
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5),
                          child: ClipRRect(
                            borderRadius: BorderRadius.all(Radius.circular(30)),
                            child: CachedNetworkImage(
                              imageUrl: userInfo==null?'':userInfo.avator,
                              width: 60,
                              height: 60,
                              fit: BoxFit.fill,
                              placeholder: (context, url) => Image.asset('assets/avator.png'),
                              errorWidget: (context, url, error) => Image.asset('assets/avator.png'),
                            ),
                          ),
                        ),
                        SizedBox(width: 10,),
                        Image.asset('assets/right.png',width: 15,height: 15,)
                      ],),
                    ),
                  ),
                  Divider(height: 1,),
                  CommonRow('账号',userInfo.userID,hasRight: false,hasLine: false,),
                ],
              ),
            ),
            Container(
              color: Colors.white,
              child: Column(
                children: [
                  CommonRow('公司名称',userInfo.companyName,hasRight: false,),
//                  CommonRow('营业执照',userInfo.authMessage,hasRight: false,),
//                  CommonRow('公司地址','浙江日普电器有限公司',hasRight: false,),
                  CommonRow('收货地址','',onTap: (){
                    push(context, AddrListPage());
                    },),
                ],
              ),
            ),
          ],);
        }),
      ),
    );
  }
  ///选取图片
  _getImage(ImageSource source) async {
    var imagePath='';
    String uuid = Uuid().v1();
    if(source==ImageSource.gallery){
      var assets=await AssetPicker.pickAssets(
          context,
          maxAssets: 1,
          requestType: RequestType.image,
          sortPathDelegate: Platform.isAndroid?CustomSortPathDelegate():SortPathDelegate.common
      );
      if(assets==null){
        return;
      }
      imagePath=(await assets[0].file).path;
    }else{
      var pick = await ImagePicker().getImage(source: source);
      if(pick==null){
        return;
      }
      imagePath=pick.path;
//      if (Platform.isIOS) {
      pick.readAsBytes().then((value) => ImageSave.saveImage(value, '$uuid.jpg'));
//      }
    }
    if(imagePath==''){
      return;
    }
    RequestUtil.post(Api.getPolicyToken, {}).then((value) async {
      var policy=policyDataFromJson(PolicyData(), value['Data']);
      String objkey =
          'TemporaryArea/APP/Avatar/${Api.userName}/$uuid.jpg';
      List imageData = await FlutterImageCompress.compressWithFile(imagePath,quality: Api.quality);
      MultipartFile multipartFile = MultipartFile.fromBytes(
        imageData,
        // 文件名
        filename: objkey,
        // 文件类型
        contentType: MediaType("image", "jpg"),
      );
      //表单需要的参数: AccessKeyId、AccessKeySecret、SecurityToken;
      FormData formdata = new FormData.fromMap({
        //文件名，随意
        'name': objkey,
        //"可以填写文件夹名（对应于oss服务中的文件夹）/" + fileName
        'key': objkey, //上传后的文件名
        'policy': policy.policy,
        //Bucket 拥有者的AccessKeyId。
        'OSSAccessKeyId': policy.accessid,
        //让服务端返回200，不然，默认会返回204
        'success_action_status': '200',
        'Signature': policy.signature,
        'file': multipartFile
        //必须放在参数最后
      });
      //然后通过存储地址直接把表单(formdata)上传上去;
      Dio dio = Dio();
      dio.options.responseType = ResponseType.plain;
      Response response =
      await dio.post(policy.host, data: formdata);
      if (response.statusCode == 200) {
        print(policy.host + objkey);
        avatarUrl=policy.host + objkey;
        RequestUtil.post(Api.uploadAvator, {
          'UserID': Api.userName,
          'Avator': avatarUrl,
        }).then((value) => this.setState(() {
          if (value['Data']['code']==0) {
            context.read<User>().getUserInfo(context,getCount: false);
          } else {
            showToast( value['Data']['msg']);
          }
        }));
      }else{
        showToast('上传失败，请重试。');
        RequestUtil.hiddenLoadingDialog(context);
      }
    });
  }
}

class CommonRow extends StatelessWidget {
  final String name;
  final String value;
  final bool hasRight;
  final bool hasLine;
  final GestureTapCallback onTap;


  CommonRow(this.name, this.value, {this.hasRight=true, this.hasLine=true,this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 20,horizontal: 10),
            child: Row(children: [
              Expanded(child: Text(name)),
              Text(value),
              SizedBox(width: 10,),
              Visibility(visible:hasRight,child: Image.asset('assets/right.png',width: 15,height: 15,))
            ],),
          ),
          Visibility(visible: hasLine,child: Divider(height: 1,)),
        ],
      ),
    );
  }
}

